package com.cn.jms;

import java.io.IOException;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.log4j.Logger;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

/**
 * 将ActiveMQTextMessage类型的消息和Spring—Integration中的消息转换
 * 
 * @author Administrator
 * 
 */
public class ActiveMQTextMessageConverter implements MessageConverter {
	public Logger logger = Logger.getLogger(ActiveMQTextMessageConverter.class);

	
	public Object fromMessage(Message msg) throws JMSException,
			MessageConversionException {
		logger.debug("fromMessage into");
		ActiveMQTextMessage activeMsg = (ActiveMQTextMessage) msg;
		String userID = null;
		String groupID = null;
		String messageID = null;
		String correlationId = null;
		try {
			userID = (String) activeMsg.getProperty("tel");
			groupID = (String) activeMsg.getProperty("groupID");
			messageID = (String) activeMsg.getProperty("messageID");
			correlationId = (String) activeMsg.getProperty("correlationId");
		} catch (IOException e) {
			e.printStackTrace();
		}
		String payload = activeMsg.getText();
		org.springframework.integration.Message<String> result = MessageBuilder
				.withPayload(payload).setCorrelationId(correlationId)
				.setHeader("messageID", messageID).setHeader("userID", userID)
				.setHeader("groupID", groupID)
				.setHeader("correlationId", correlationId).build();
		return result;
	
	}

	
	public Message toMessage(Object msg, Session session) throws JMSException,
			MessageConversionException {
		@SuppressWarnings("unchecked")
		org.springframework.integration.Message<String> siMessage = ((org.springframework.integration.Message<String>) msg);
	String payload =siMessage.getPayload();
//		MessageHeaders messageHeaders = siMessage.getHeaders();
//		String messageID = (String) messageHeaders.get("messageID");
//		String userID = (String) messageHeaders.get("tel");
	
		ActiveMQObjectMessage activeMsg = new ActiveMQObjectMessage();
		try {
			activeMsg.setProperty("payload", payload);
			
			logger.debug("消息转换为MQ消息="+payload);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return activeMsg;
	}

}
